package com.whl.sm.service.impl.parking;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whl.sm.common.result.Result;
import com.whl.sm.mapper.parking.ParkingBillMapper;
import com.whl.sm.model.expense.ExpenseType;
import com.whl.sm.model.parking.ParkingBill;
import com.whl.sm.model.parking.ParkingLots;
import com.whl.sm.model.parking.ParkingRecord;
import com.whl.sm.service.expense.ExpenseTypeService;
import com.whl.sm.service.parking.ParkingBillService;
import com.whl.sm.service.parking.ParkingLotsService;
import com.whl.sm.service.parking.ParkingRecordService;
import com.whl.sm.service.system.OrgUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wuhaolun
 * @since 2021-11-01
 */
@Slf4j
@Service
public class ParkingBillServiceImpl extends ServiceImpl<ParkingBillMapper, ParkingBill> implements ParkingBillService {

    @Autowired
    private ParkingRecordService parkingRecordService;

    @Autowired
    private ParkingLotsService parkingLotsService;

    @Autowired
    private ExpenseTypeService expenseTypeService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private OrgUserService orgUserService;

    @Override
    public Result getBillPrice(String recordId) {
        try{
            double billPrice = 0;
            ParkingRecord relateRecord = parkingRecordService.getById(recordId);
            if (relateRecord.getVisible()==0){
                return Result.build(444,"费用已支付！");
            }
            if (redisTemplate.hasKey(recordId)){
                billPrice = Double.parseDouble(String.valueOf(redisTemplate.opsForValue().get(recordId)));
            }
            else {
                ParkingLots relateLots = parkingLotsService.getById(relateRecord.getParkingLotsId());
                if (relateLots.getExpenseId() != null){
                    ExpenseType expenseType = expenseTypeService.getById(relateLots.getExpenseId());
                    Date currentDate = new Date();
                    long distantTime = currentDate.getTime()-relateRecord.getEnterTime().getTime();
                    billPrice = (distantTime/1000/60/60)*expenseType.getUnitPrice()+expenseType.getDefaultPrice();
                    billPrice = billPrice <= 0 ? 0:billPrice;
                }
                redisTemplate.opsForValue().set(recordId,String.valueOf(billPrice),5, TimeUnit.MINUTES);
            }
            return Result.ok(billPrice);
        }
        catch (Exception e){
            log.error("停车场管理------>获取停车费用错误"+e.getMessage());
            return Result.fail();
        }
    }

    @Override
    public Result getBillPriceByPlate(String licensePlate) {
        licensePlate = licensePlate.toUpperCase();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("license_plate",licensePlate);
        queryWrapper.eq("visible",1);
        queryWrapper.ne("is_del",1);
        List<ParkingRecord> hasList = parkingRecordService.list(queryWrapper);
        if (hasList.size()>0){
            Result rtPrice =  getBillPrice(hasList.get(0).getId());
            if (rtPrice.isOk()){
                Map<String,Object> rtData = new HashMap<>();
                rtData.put("billPrice",rtPrice.getData());
                rtData.put("recordId",hasList.get(0).getId());
                rtData.put("enterTime",hasList.get(0).getEnterTime());
                rtPrice.setData(rtData);
            }
            return rtPrice;
        }else {
            return Result.build(444,"没有停车记录");
        }

    }


    @Override
    public Result addRecordBill(String recordId) {
        try {
            if (!redisTemplate.hasKey(recordId)){
                return Result.build(444,"请重新获取账单！");
            }
            String userId = orgUserService.getCurrentUserId();
            double billPrice = Double.parseDouble(String.valueOf(redisTemplate.opsForValue().get(recordId)));
            ParkingRecord relateRecord = parkingRecordService.getById(recordId);
            relateRecord.setLeaveTime(new Date());
            relateRecord.setVisible(0);
            parkingRecordService.updateById(relateRecord);

            ParkingBill insertBill = new ParkingBill();
            insertBill.setParkingLotsId(relateRecord.getParkingLotsId());
            insertBill.setBillPrice(billPrice);
            insertBill.setParkingRecordId(recordId);
            insertBill.setPaymentTime(new Date());
            insertBill.setPaymentStatus(1);
            insertBill.setPayer(userId);
            save(insertBill);
        }catch (Exception e){
            log.error("停车场管理------>生成账单错误"+e.getMessage());
            return Result.fail();
        }
        return Result.ok();
    }


}







